package org.enhance.common.util.encryption;

import org.apache.commons.lang3.StringUtils;
import org.enhance.common.exception.AssertionException;
import org.enhance.common.util.Assertion;

public class DesensitizationUtil {
	private DesensitizationUtil() {
		throw new IllegalStateException("Constant class");
	}

	public static final String KEY_AESKEY = "aes.key";

	public static String idCardDes(String encryptIdCard) {
		return idCardDes(encryptIdCard, true);
	}

	public static String idCardDes(String encryptIdCard, boolean withEncr) {
		if (StringUtils.isEmpty(encryptIdCard)) {
			return null;
		}
		String aesKey = System.getProperty(KEY_AESKEY);
		Assertion.notEmpty(aesKey, "lack config of aes.key!");
		String idCard = Base64Util.decode(AesUtil.decrypt(aesKey, encryptIdCard));
		if(withEncr) {
			idCard = originalIdCardDes(idCard);
		}
		return idCard;
	}

	public static String originalIdCardDes(String originalIdCard) {
		if (StringUtils.isEmpty(originalIdCard)) {
			return null;
		}

		String idCard;
		if (originalIdCard.length() == 15) {
			idCard = originalIdCard.replaceAll("(\\w{6})\\w*(\\w{3})", "$1******$2");
		} else if (originalIdCard.length() == 18) {
			idCard = originalIdCard.replaceAll("(\\w{6})\\w*(\\w{3})", "$1*********$2");
		} else {
			throw new AssertionException("未知格式身份证号：" + originalIdCard);
		}
		return idCard;
	}

	public static String mobileDes(String origionalMobile) {
		if (StringUtils.isEmpty(origionalMobile)) {
			return null;
		}
		return origionalMobile.replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
	}
}
